
import std.stdio:writefln;

import std.string: toStringz;

import maths.Vec;

import utils.Singleton;

import derelict.sdl.sdl;

import Lines;
import Display;

class Screen{
	mixin SingletonMix;
	SDL_Surface *scr;
	uint width = 800;
	uint height = 600;
	uint bitsPerPixel = 32;
	bool fullscreen = false;
	uint background = 0x7F7F7F;
	char[] caption = "LOD";
	private bool mustLock = true;

	void initialize(){
		initSDL();
		mustLock = SDL_MUSTLOCK(scr);
	}

	void show(){
		if(mustLock) SDL_LockSurface(scr);
		clearScreen(scr);
		drawFrame();
		if(mustLock) SDL_UnlockSurface(scr);
		SDL_UpdateRect(scr, 0, 0, 0, 0);
	}

	void begin(){
		if(mustLock) SDL_LockSurface(scr);
		clearScreen(scr);
		if(mustLock) SDL_UnlockSurface(scr);
	}

	void end(){
		SDL_UpdateRect(scr, 0, 0, 0, 0);
	}

	void drawFrame(){
	}

	void drawWiredTriangle(vec3[3] verts){
//		writefln("###################");
		vec2 v1 = display.project(verts[0]);
		vec2 v2 = display.project(verts[1]);
		vec2 v3 = display.project(verts[2]);
//		writefln(v1);
//		writefln(v2);
//		writefln(v3);
		line(scr, v1, v2, 1234);
		line(scr, v2, v3, 1234);
		line(scr, v1, v3, 1234);
	}

	private void initSDL(){
		uint sdlFlags = SDL_HWSURFACE;
		DerelictSDL.load();

		if(fullscreen)
			sdlFlags |= SDL_FULLSCREEN;

		SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
		SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
		scr = SDL_SetVideoMode(width, height, bitsPerPixel, sdlFlags );
		SDL_WM_SetCaption(toStringz(caption), null);
	}

	private void clearScreen(SDL_Surface *surface){
		uint *p = cast(uint *)surface.pixels;
		p[0..surface.w * surface.h] = background;
	}

	~this(){
		SDL_Quit();
		DerelictSDL.unload();
	}


}

alias SingletonGetter!(Screen) screen;
